<template>
  <div class="main-page">
    <PageSearch :search-form-config="searchFormConfig" :form-data.sync="formData" @searchBtnClick="handleSearch" />
    <el-row type="flex" align="middle" justify="end">
      <el-col>
        默认密码为手机号后6位
      </el-col>
      <el-button type="primary" icon="el-icon-plus" size="medium" @click="handleCreateUser">
        新建用户
      </el-button>
    </el-row>
    <PageContent ref="pageContent" :form-data="formData" :content-table-config="contentConfig">
      <template #billType="{ row }">
        {{ row.billType === 0 ? '月结' : row.billType === 1 ? '周结' : row.billType === 2 ? '日结' : '-' }}
      </template>
      <template #operate="{ row }">
        <el-button type="text" size="small" icon="el-icon-edit" @click="handleCreateUser(row)">
          编辑
        </el-button>
        <el-button type="text" size="small" icon="el-icon-refresh-left" @click="handleServiceUser(row)">
          设置业务经理
        </el-button>
        <el-button type="text" size="small" icon="el-icon-edit" @click="handleChangeTeam(row)">
          修改团队
        </el-button>
        <el-button type="text" size="small" icon="el-icon-edit-outline" @click="handleChangeReferrer(row)">
          修改推荐人
        </el-button>
        <el-button type="text" size="small" icon="el-icon-refresh-left" @click="handleResetPwd(row)">
          重置密码
        </el-button>
      </template>
    </PageContent>

    <PageModal ref="pageModal" :modal-form-data="modalFormData" :modal-form-config="modalFormConfig"
      :visible.sync="dialogVisible" :title="title" :btn-loading="confirmBtnLoading" @confirm="handleConfirm" />
    <!-- 修改推荐人 -->
    <PageModal :modal-form-data="modalFormData" :modal-form-config="referrerModalFormConfig"
      :visible.sync="dialogReferrerVisible" title="修改推荐人" :btn-loading="confirmBtnLoading"
      @confirm="handleReferrerConfirm" />
    <!-- 修改团队 -->
    <PageModal :modal-form-data="modalFormData" :modal-form-config="teamFormConfig" :visible.sync="dialogTeamVisible"
      title="修改团队" :btn-loading="confirmBtnLoading" @confirm="handleTeamConfirm" />
    <!-- 修改推荐人 -->
    <PageModal :modal-form-data="modalFormData" :modal-form-config="serviceModalFormConfig"
      :visible.sync="dialogServiceVisible" title="修改业务经理" :btn-loading="confirmBtnLoading"
      @confirm="handleServiceConfirm" />
  </div>
</template>

<script>
import { contentConfig } from "./config/content.config";
import { searchFormConfig } from "./config/search.config";
import { modalFormConfig } from "./config/modal.config";
import { teamFormConfig } from "./config/teamModal.config";
import { referrerModalFormConfig } from "./config/referrerModal.config";
import { serviceModalFormConfig } from "../team/config/serviceModal.config";
import {
  fetchCreateUser,
  fetchUserDetail,
  fetchRoleList,
  fetchLevelList,
  fetchUpdateReferrer,
  fetchUpdateService,
  fetchResetPassword,
  fetchUpdateTeam
} from "@/api/useManage";
import { getUserList } from "@/api/user";
import { userTeamList } from "@/api/userTeam";
export default {
  name: "User",
  data() {
    return {
      contentConfig,
      searchFormConfig,
      modalFormConfig,
      referrerModalFormConfig,
      serviceModalFormConfig,
      teamFormConfig,
      btnLoading: false,
      confirmBtnLoading: false,
      dialogVisible: false,
      dialogReferrerVisible: false,
      formData: {}, // 搜索表单数据
      title: "新建用户",
      modalFormData: {
        name: "",
        phone: "",
        roleIds: [],
        gradeLevel: "",
        order: undefined,
        teamId: '',
      }, // 模态框表单数据
      teamFormData: {},
      dialogTeamVisible: false,
      getRowUserId: '',
      dialogServiceVisible: false,
    };
  },
  mounted() {
    this.getTeam();
    this.getUserListReq();
  },
  methods: {
    handleServiceConfirm(data) {
      this.confirmBtnLoading = true;
      const { id, serviceUserId } = { ...this.modalFormData, ...data };
      fetchUpdateService({ userId: id, serviceUserId })
        .then(() => {
          this.$message.success("操作成功。");
          this.dialogServiceVisible = false;
          this.handleSearch();
        })
        .finally(() => {
          this.confirmBtnLoading = false;
        });
    },
    getTeam() {
      userTeamList().then((res) => {
        let resArr = [];
        for (let i = 0; i < res.data.length; i++) {
          resArr.push({
            label: res.data[i].name,
            value: res.data[i].id
          })
        }
        this.searchFormConfig.formItems[1].options = resArr;
        this.teamFormConfig.formItems[0].options = resArr;
      });
    },
    handleSearch() {
      this.$refs.pageContent.queryTblMain();
    },
    handleServiceUser({id}) {
      fetchUserDetail(id).then((res) => {
        this.modalFormData = { id, ...res.data };
        this.dialogServiceVisible = true;
      });
      // this.modalFormData = row;
      // this.dialogServiceVisible = true;
    },
    initSelect() {
      //获取角色列表
      fetchRoleList().then((res) => {
        this.modalFormConfig.formItems[2].options = res.data?.map((item) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      });

      //获取等级列表
      fetchLevelList().then((res) => {
        this.modalFormConfig.formItems[3].options = res.data?.map((item) => {
          return {
            label: item.name,
            value: item.level,
          };
        });
      });
    },
    getUserListReq() {
      getUserList({ pageSize: 10000, pageNum: 1 }).then((res) => {
        this.referrerModalFormConfig.formItems.forEach((item) => {
          if (item.field === "referrerId") {
            item.options = res.data?.userList.map((it) => {
              return {
                label: `${it.name}（${it.phone}）`,
                value: it.id,
              };
            });
          }
        });
        this.serviceModalFormConfig.formItems.forEach((item) => {
          if (item.field === "serviceUserId") {
            item.options = res.data?.userList.map((it) => {
              return {
                label: `${it.name}（${it.phone}）`,
                value: it.id,
              };
            });
          }
        });
      });
    },

    handleCreateUser({ id }) {
      this.initSelect();
      if (id) {
        this.title = "编辑用户";
        fetchUserDetail(id).then((res) => {
          this.modalFormData = { ...res.data };
        });
      } else {
        this.title = "新建用户";
        this.modalFormData = {
          name: "",
          phone: "",
          roleIds: [],
          gradeLevel: "",
          order: undefined,
        };
      }
      this.dialogVisible = true;
    },
    handleChangeReferrer({ id }) {
      fetchUserDetail(id).then((res) => {
        this.modalFormData = { id, ...res.data };
        this.dialogReferrerVisible = true;
      });
    },
    handleChangeTeam({ id }) {
      console.log(id);
      this.getRowUserId = id;
      this.dialogTeamVisible = true;
    },
    handleTeamConfirm(data) {
      this.confirmBtnLoading = true;
      fetchUpdateTeam({ teamId: data.teamId, userId: this.getRowUserId }).then(() => {
        this.$message.success("操作成功。");
        this.dialogTeamVisible = false;
        this.getRowUserId = '';
        this.handleSearch();
      }).finally(() => {
        this.confirmBtnLoading = false;
      });
    },
    handleReferrerConfirm(data) {
      this.confirmBtnLoading = true;
      const { id, referrerId } = { ...this.modalFormData, ...data };
      fetchUpdateReferrer({ id, referrerId })
        .then(() => {
          this.$message.success("操作成功。");
          this.dialogReferrerVisible = false;
          this.handleSearch();
        })
        .finally(() => {
          this.confirmBtnLoading = false;
        });
    },
    handleResetPwd({ id }) {
      this.$confirm('确定重置密码？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        fetchResetPassword(id).then(() => {
          this.$message.success("操作成功。");
        });
      }).catch(() => {

      });
    },
    handleConfirm(data) {
      this.confirmBtnLoading = true;
      const params = {
        ...this.modalFormData,
        ...data,
      };
      delete params.referrerId;
      fetchCreateUser(params)
        .then(() => {
          this.$message.success("操作成功。");
          this.dialogVisible = false;
          this.handleSearch();
        })
        .finally(() => {
          this.confirmBtnLoading = false;
        });
    },
  },
};
</script>
